package com.yilizhiyou.controller;

import com.yilizhiyou.common.Result;
import com.yilizhiyou.entity.ScenicSpot;
import com.yilizhiyou.service.AiSearchService;
import com.yilizhiyou.controller.ScenicSpotController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * AI搜索控制器
 * 集成DeepSeek API的智能搜索功能
 * 
 * @author 伊犁智游开发团队
 * @since 1.0.0
 */
@RestController
@RequestMapping("/ai-search")
@Tag(name = "AI搜索", description = "基于DeepSeek API的智能搜索功能")
@CrossOrigin(origins = "*")
public class AiSearchController {

    private static final Logger log = LoggerFactory.getLogger(AiSearchController.class);
    
    @Autowired
    private AiSearchService aiSearchService;
    
    @Autowired
    private ScenicSpotController scenicSpotController;

    @PostMapping("/search")
    @Operation(summary = "AI智能搜索", description = "使用DeepSeek API进行智能搜索")
    public Result<Map<String, Object>> aiSearch(
            @Parameter(description = "搜索查询") @RequestParam String query,
            @Parameter(description = "上下文信息") @RequestParam(required = false) String context) {
        
        log.info("AI搜索请求: query={}, context={}", query, context);
        
        try {
            Map<String, Object> result = aiSearchService.aiSearch(query, context);
            return Result.success("AI搜索成功", result);
        } catch (Exception e) {
            log.error("AI搜索失败", e);
            return Result.error("AI搜索失败: " + e.getMessage());
        }
    }

    @GetMapping("/suggestions")
    @Operation(summary = "获取搜索建议", description = "基于部分查询获取AI搜索建议")
    public Result<List<String>> getSearchSuggestions(
            @Parameter(description = "部分查询") @RequestParam String partialQuery) {
        
        log.info("获取搜索建议: partialQuery={}", partialQuery);
        
        try {
            List<String> suggestions = aiSearchService.getSearchSuggestions(partialQuery);
            return Result.success("获取搜索建议成功", suggestions);
        } catch (Exception e) {
            log.error("获取搜索建议失败", e);
            return Result.error("获取搜索建议失败: " + e.getMessage());
        }
    }

    @PostMapping("/recommend")
    @Operation(summary = "智能景点推荐", description = "基于查询进行智能景点推荐")
    public Result<List<ScenicSpot>> intelligentRecommendation(
            @Parameter(description = "用户查询") @RequestParam String query) {
        
        log.info("智能景点推荐: query={}", query);
        
        try {
            List<ScenicSpot> allSpots = scenicSpotController.getAllSpots().getData();
            List<ScenicSpot> recommendations = aiSearchService.intelligentSpotRecommendation(query, allSpots);
            return Result.success("智能推荐成功", recommendations);
        } catch (Exception e) {
            log.error("智能推荐失败", e);
            return Result.error("智能推荐失败: " + e.getMessage());
        }
    }

    @PostMapping("/semantic")
    @Operation(summary = "语义搜索", description = "基于自然语言的语义搜索")
    public Result<List<ScenicSpot>> semanticSearch(
            @Parameter(description = "自然语言查询") @RequestParam String query) {
        
        log.info("语义搜索: query={}", query);
        
        try {
            List<ScenicSpot> allSpots = scenicSpotController.getAllSpots().getData();
            List<ScenicSpot> results = aiSearchService.semanticSearch(query, allSpots);
            return Result.success("语义搜索成功", results);
        } catch (Exception e) {
            log.error("语义搜索失败", e);
            return Result.error("语义搜索失败: " + e.getMessage());
        }
    }

    @PostMapping("/summary")
    @Operation(summary = "生成搜索摘要", description = "为搜索结果生成AI摘要")
    public Result<String> generateSearchSummary(
            @Parameter(description = "搜索查询") @RequestParam String query,
            @Parameter(description = "搜索结果") @RequestBody List<ScenicSpot> results) {
        
        log.info("生成搜索摘要: query={}, resultsCount={}", query, results.size());
        
        try {
            String summary = aiSearchService.generateSearchSummary(query, results);
            return Result.success("生成搜索摘要成功", summary);
        } catch (Exception e) {
            log.error("生成搜索摘要失败", e);
            return Result.error("生成搜索摘要失败: " + e.getMessage());
        }
    }

    @GetMapping("/enhanced-search")
    @Operation(summary = "增强搜索", description = "结合传统搜索和AI搜索的增强搜索功能")
    public Result<Map<String, Object>> enhancedSearch(
            @Parameter(description = "搜索关键词") @RequestParam String keyword) {
        
        log.info("增强搜索: keyword={}", keyword);
        
        try {
            // 1. 传统搜索
            List<ScenicSpot> traditionalResults = scenicSpotController.searchSpots(keyword).getData();
            
            // 2. AI语义搜索
            List<ScenicSpot> aiResults = aiSearchService.semanticSearch(keyword, scenicSpotController.getAllSpots().getData());
            
            // 3. 合并去重结果
            List<ScenicSpot> combinedResults = combineSearchResults(traditionalResults, aiResults);
            
            // 4. 生成AI摘要
            String summary = aiSearchService.generateSearchSummary(keyword, combinedResults);
            
            // 5. 构建返回结果
            Map<String, Object> result = Map.of(
                "keyword", keyword,
                "traditionalResults", traditionalResults,
                "aiResults", aiResults,
                "combinedResults", combinedResults,
                "summary", summary,
                "totalCount", combinedResults.size()
            );
            
            return Result.success("增强搜索成功", result);
        } catch (Exception e) {
            log.error("增强搜索失败", e);
            return Result.error("增强搜索失败: " + e.getMessage());
        }
    }

    /**
     * 合并搜索结果，去重
     */
    private List<ScenicSpot> combineSearchResults(List<ScenicSpot> traditionalResults, List<ScenicSpot> aiResults) {
        // 使用LinkedHashMap保持顺序并去重
        Map<Long, ScenicSpot> resultMap = new java.util.LinkedHashMap<>();
        
        // 先添加传统搜索结果
        if (traditionalResults != null) {
            for (ScenicSpot spot : traditionalResults) {
                resultMap.put(spot.getId(), spot);
            }
        }
        
        // 再添加AI搜索结果
        if (aiResults != null) {
            for (ScenicSpot spot : aiResults) {
                resultMap.putIfAbsent(spot.getId(), spot);
            }
        }
        
        return new java.util.ArrayList<>(resultMap.values());
    }
}
